﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for DBConnection.xaml
    /// </summary>
    public partial class DBConnection : Window
    {
        SqlDataAdapter da;
        DataSet ds = new DataSet();

        // Build the Connection String and create a SQL Connection object

        static String cnnStr = "Data Source = localhost; Integrated Security = SSPI; MultipleActiveResultSets=True";

        SqlConnection cnn = new SqlConnection(cnnStr);

        private MainWindow mainForm = null;
        public DBConnection()
        {
            
            InitializeComponent();
        }
        public DBConnection(MainWindow calledForm)
        {
            
            mainForm = calledForm as MainWindow;
            InitializeComponent();
           
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtBoxServerName.IsReadOnly = true;
            txtBoxUserName.IsReadOnly = true;
        }

        private void rdbtnLogin_Checked(object sender, RoutedEventArgs e)
        {
            if (rdbtnLogin.IsChecked == true)
            {
                txtBoxServerName.Text = "";
                txtBoxUserName.Text = "";
                txtBoxPwd.Password = "";
                txtBoxPwd.IsEnabled = false;
                txtBoxServerName.IsEnabled = false;
                txtBoxUserName.IsEnabled = false;
            }
            else
            {
                txtBoxPwd.IsEnabled = true;
                txtBoxServerName.IsEnabled = true;
                txtBoxUserName.IsEnabled = true;
            }
            
        }
       
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Cursor = Cursors.Wait;
                String cnnStr = string.Empty;
                if (txtBoxServerName.Text != "" || txtBoxUserName.Text != "" || txtBoxPwd.Password != "" || rdbtnSQLLogin.IsChecked == true)
                {
                    cnnStr = "Data Source =" + txtBoxServerName.Text + "; User ID=" + txtBoxUserName.Text + ";Password=" + txtBoxPwd.Password + ";";
                    cnn.ConnectionString = cnnStr;

                   
                    if (txtBoxServerName.Text == "" || txtBoxUserName.Text == "" || txtBoxPwd.Password == "")
                    {
                        throw new Exception();
                    }

                    if (cnn.State.ToString().Equals("Closed"))
                    {
                        cnn.Open();
                    }

                }

                else
                {

                    cnnStr = "Data Source = localhost; Integrated Security = SSPI;";
                    cnn.ConnectionString = cnnStr;


                    if (cnn.State.ToString().Equals("Closed"))
                    {
                        cnn.Open();
                    }
                }

                MainWindow.ConnectionString = cnnStr;

                // Create a SQL Command object from the connection object and setup the SELECT command
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT name FROM sys.databases";

                // Create the data adapter to use to get the data and handle connecting to the DB
                da = new SqlDataAdapter(cmd);

                // Get the data from the database. .
                ds.Clear();

                da.Fill(ds, "sys.databases");

                // Connect the cobo box to the data source from where the data is comming from
                // In this case the Customers data table in the dataset.
                //DBcomboBox.DataSource = ds.Tables["sys.databases"];


                DataRow dr = ds.Tables[0].NewRow();
                dr["name"] = "0";
                dr["name"] = "Please select database...";
                ds.Tables[0].Rows.InsertAt(dr, 0);
                DataTable table = ds.Tables[0];
                ObservableCollection<object> collection = new ObservableCollection<object>();
                collection.Add(ds.Tables[0]);

                this.mainForm.DBcomboBox.ItemsSource = table.DefaultView;


                this.mainForm.DBcomboBox.DisplayMemberPath = "name";

                // Tell the combo box what collumn to use with the displayed value, value is not displayed
                this.mainForm.DBcomboBox.SelectedValuePath = "name";


                // Tell the combo box what collumn to display to the user
                //DBcomboBox.DisplayMember = "name";

                // Tell the combo box what collumn to use with the displayed value, value is not displayed
                //DBcomboBox.ValueMember = "name";

                // make it readonly

                //this.mainForm.DBcomboBox.DropDownStyle = ComboBoxStyle.DropDownList;



                //Cursor= Cursors.d;
                Cursor.Dispose();
                this.mainForm.DBcomboBox.SelectedIndex = 0;
                cnn.Close();
                this.Hide();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please enter correct username/password," + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Cursor = Cursors.Arrow;
            }
        }

        private void rdbtnSQLLogin_Checked(object sender, RoutedEventArgs e)
        {
            txtBoxServerName.IsReadOnly = false;
            txtBoxUserName.IsReadOnly = false;
            txtBoxPwd.IsEnabled = true;
            txtBoxServerName.IsEnabled = true;
            txtBoxUserName.IsEnabled = true;
            txtBoxServerName.Tag = "Please enter a Server name";
            txtBoxUserName.Tag = "Please enter a User name";
            txtBoxPwd.Tag = "Please enter a Password";
        }
        
        private void txtBoxServerName_TextChanged(object sender, EventArgs e)
        {
            //Store the back up of Current Cursor Possition.
            int cusorpos = txtBoxServerName.SelectionStart;

            if (false == string.IsNullOrEmpty(txtBoxServerName.Text))
            {
                if (txtBoxServerName.Text[0] == ' ')
                {
                    //Trim Spaces at beginning.
                    txtBoxServerName.Text = txtBoxServerName.Text.TrimStart(' ');

                    //Set the Cursor position to current Position. 
                    txtBoxServerName.SelectionStart = cusorpos;
                }
            }
        }

        private void txtBoxUserName_TextChanged(object sender, EventArgs e)
        {
            int cusorpos = txtBoxUserName.SelectionStart;

            if (false == string.IsNullOrEmpty(txtBoxUserName.Text))
            {
                if (txtBoxUserName.Text[0] == ' ')
                {
                    //Trim Spaces at beginning.
                    txtBoxUserName.Text = txtBoxUserName.Text.TrimStart(' ');

                    //Set the Cursor position to current Position. 
                    txtBoxUserName.SelectionStart = cusorpos;
                }
            }
        }

        
        private void txtBoxPwd_TextChanged(object sender, EventArgs e)
        {
            if (false == string.IsNullOrEmpty(txtBoxPwd.Password))
            {
                if (txtBoxPwd.Password[0] == ' ')
                {
                    //Trim Spaces at beginning.
                    txtBoxPwd.Password = txtBoxPwd.Password.TrimStart(' ');
                }
            }

        }
    }
}
